package api

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"zsc-boot/app/customer/model"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

type CustomerChannel struct {
}

func (c *CustomerChannel) Create(ctx *gin.Context) {
	var req model.CustomerChannel
	_ = ctx.Bind(&req)
	req.SecretKey = uuid.New().String()
	req.UUID = uuid.New().String()
	if err := orm.Create[model.CustomerChannel](req); err != nil {
		web.FailResponse(ctx, err, "创建失败")
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

func (c *CustomerChannel) Update(ctx *gin.Context) {
	var req model.CustomerChannel
	_ = ctx.Bind(&req)
	if err := orm.Update[model.CustomerChannel](req, req.ID); err != nil {
		web.FailResponse(ctx, err, "修改失败")
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

func (c *CustomerChannel) Detail(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)
	data, err := orm.Detail[model.CustomerChannel](int(req.ID))
	if err != nil {
		web.FailResponse(ctx, err, "查询失败")
		return
	} else {
		web.SuccessResponse(ctx, data)
	}
}

func (c *CustomerChannel) List(ctx *gin.Context) {
	var req core.PageInfo
	_ = ctx.Bind(&req)

	var list []model.CustomerChannel

	if err := orm.GetDb().Where("remark != ?", "旧系统导入").Order("id desc").Find(&list).Error; err != nil {
		web.FailResponse(ctx, err, "查询失败")
		return
	} else {
		web.SuccessResponse(ctx, list)
	}
}

func (c *CustomerChannel) Del(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)

	var customer model.Customer
	if err := orm.GetDb().Where("channel_id = ?", req.ID).Find(&customer).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	if customer.ID != 0 {
		web.FailResponse(ctx, nil, "请先移除该渠道下的客户")
		return
	}

	if err := orm.Delete[model.CustomerChannel](req.ID); err != nil {
		web.FailResponse(ctx, err, "删除失败")
	} else {
		web.SuccessResponse(ctx, nil)
	}
}
